<template>
	<view class="u-p-30">
		<view class="u-demo-block combox u-p-20">
			<view class="u-demo-block__content">
				<!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
				<u--form labelPosition="left" ref="form1">
					<u-form-item :labelWidth='100' label="手机号" borderBottom>
						<u--input v-model="userInfo.phone" border="none" placeholder="请输入手机号"></u--input>
					</u-form-item>
					<u-form-item :labelWidth='100' label="验证码">
						<u--input v-model="userInfo.code" border="none" maxlength='4' placeholder="请填写验证码"></u--input>
						<u-button slot="right" @tap="getCode" :text="tips" type="error" size="mini"
							:disabled="disabled1"></u-button>
					</u-form-item> 
				</u--form>
				<u-code ref="uCode" @change="codeChange" seconds="60" @start="disabled1 = true"
					@end="disabled1 = false"></u-code>
				<u-button type="primary" text="提交" customStyle="margin-top: 50px" @click="submit"></u-button>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				disabled1: false,
				userInfo: {
					phone: "",
					code: ""
				},
				tips: '验证码',
			}
		},

		methods: {
			codeChange(text) {
				this.tips = text;
			},
			getCode() {
				if (!this.userInfo.phone) {
					uni.$u.toast('请输入手机号');
					return
				}
				if (this.$refs.uCode.canGetCode) {
					// 模拟向后端请求验证码
					uni.showLoading({
						title: '正在获取验证码'
					})
					let data = {
						phone: this.userInfo.phone,
						appId: 'wx3ce852389cb6ded0'
					}
					this.$api.bindPhoneSendCodeApi(data).then(res => {
						setTimeout(() => {
							uni.hideLoading();
							// 这里此提示会被this.start()方法中的提示覆盖
							uni.$u.toast('验证码已发送');
							// 通知验证码组件内部开始倒计时
							this.$refs.uCode.start();
						}, 2000);
					})
				} else {
					uni.$u.toast('倒计时结束后再发送');
				}
			},

			submit() {
				let data = {
					phone: this.userInfo.phone,
					code: this.userInfo.code,
					appId: 'wx3ce852389cb6ded0'
				}
				this.$api.bindPhoneApi(data).then(res => {
					uni.$u.toast('手机号绑定成功');
					uni.setStorageSync('phone', this.userInfo.phone)
					setTimeout(() => {
						uni.navigateBack()
					}, 1000)
				})
			},

		},
	}
</script>

<style lang="scss">

</style>